package org.msfj.common.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import org.msfj.common.submail.*;
import cn.hutool.core.date.DateUtil;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Description:SubMail短信发送工具类
 * @Author: like
 * @Date: 2017-06-01 13:23
 * @Version: 1.0
 * @Created in idea by autoCode
 */
public class SubMailUtil {

    @Autowired
    public SubMailUtil(SubmailConfig submailConfig) {
        this.submailConfig = submailConfig;
    }

    private Logger logger = LoggerFactory.getLogger(SubMailUtil.class);

    private SubmailConfig submailConfig;

    public boolean sendSubmailVoice(String projectId, SubMailMessage subMailMessage) {
        return sendSubmailVoice(projectId, new SubMailMessages(subMailMessage));
    }

    public boolean sendSubmailVoice(String projectId, SubMailMessages subMailMessageList) {
        if (submailConfig.isMock()) {
            return sendSubMailMessageMock(projectId, subMailMessageList);
        }
        String multi = "";
        if (subMailMessageList.getList() != null && !subMailMessageList.getList().isEmpty()) {
            multi = JSONUtil.toJsonStr(subMailMessageList.getList());
        }
        String info;
        HttpClient httpclient = new HttpClient();
        PostMethod post = new PostMethod(this.submailConfig.getVoiceSendUrl());
        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
        post.addParameter("appid", submailConfig.getVoiceAppId());
        post.addParameter("project", projectId);
        post.addParameter("multi", multi);
        post.addParameter("signature", submailConfig.getVoiceAppKey());
        try {
            httpclient.executeMethod(post);
            info = new String(post.getResponseBody(), "utf-8");
            JSONArray jsonArray = JSONUtil.parseArray(info);

            for (int i = 0; i < jsonArray.size(); i++) {
                SubMailResult messageResultVo = JSONUtil.toBean(JSONUtil.parseObj(jsonArray.get(i)), SubMailResult.class);
                if ("success".equals(messageResultVo.getStatus())) {
                    if (logger.isInfoEnabled()) {
                        logger.info("成功发送语音通知给[" + messageResultVo.getTo() + "]");
                    }
                } else {
                    String logContent = "发送语音通知给[" + messageResultVo.getTo() + "]失败";
                    if (logger.isInfoEnabled()) {
                        logger.error(logContent);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("发送语音通知错误", e);
        }
        return true;
    }

    public boolean sendSubMailMessageMock(String projectId, SubMailMessages subMailMessageList) {
        System.out.println(String.format("模拟发送短信[%s]给[%s]", projectId, JsonObjectUtils.objectToJson(subMailMessageList)));
        return true;
    }

    public boolean sendSubMailMessage(String projectId, SubMailMessage subMailMessage) {
        return sendSubMailMessage(projectId, new SubMailMessages(subMailMessage));
    }

    public boolean sendSubMailMessage(String projectId, SubMailMessages subMailMessageList) {
        return this.sendSubMailMessageNow(projectId, subMailMessageList);
    }

    public List<SubMailTemplate> getTemplateList() {
        String info;
        List<SubMailTemplate> template = CollectionUtil.newArrayList();
        HttpClient httpclient = new HttpClient();
        String url = submailConfig.getTemplateUrl() + "?appid=" + submailConfig.getAppId() + "&signature=" + submailConfig.getAppKey();
        GetMethod getMethod = new GetMethod(url);
        try {
            httpclient.executeMethod(getMethod);
            info = new String(getMethod.getResponseBody(), "utf-8");
            SubMailResult subMailResult = JsonObjectUtils.jsonToBean(info, SubMailResult.class);
            if ("success".equals(subMailResult.getStatus())) {
                template = subMailResult.getTemplates();
            } else {
                if (logger.isInfoEnabled()) {
                    logger.error("获取submail短信模板失败，错误代码：" + subMailResult.getCode() + "，错误信息：" + subMailResult.getMsg());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return template;
    }

    public SubMailTemplate insertTemplate(SubMailTemplate subMailTemplateVo) {
        String info;
        HttpClient httpclient = new HttpClient();
        PostMethod post = new PostMethod(submailConfig.getTemplateUrl());
        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
        post.addParameter("appid", submailConfig.getAppId());
        post.addParameter("signature", submailConfig.getAppKey());
        post.addParameter("sms_title", subMailTemplateVo.getSms_title());
        post.addParameter("sms_content", subMailTemplateVo.getSms_content());
        post.addParameter("sms_signature", subMailTemplateVo.getSms_signature());
        subMailTemplateVo.setAdd_date(DateUtil.now());
        try {
            httpclient.executeMethod(post);
            info = new String(post.getResponseBody(), "utf-8");
            SubMailResult subMailResult = JSONUtil.toBean(JSONUtil.parseObj(info), SubMailResult.class);
            if ("success".equals(subMailResult.getStatus())) {
                subMailTemplateVo.setTemplate_id(subMailResult.getTemplate_id());
            } else {
                if (logger.isInfoEnabled()) {
                    logger.error("添加submail短信模板失败，错误代码：" + subMailResult.getCode() + "，错误信息：" + subMailResult.getMsg());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return subMailTemplateVo;
    }

    public boolean updateTemplate(SubMailTemplate subMailTemplateVo) {
        String info;
        boolean isSuccess = false;
        try {
            HttpClient httpclient = new HttpClient();
            PutMethod putMethod = new PutMethod(submailConfig.getTemplateUrl());
            String url = "appid=" + submailConfig.getAppId() + "&signature=" + submailConfig.getAppKey();
            url += "&template_id=" + subMailTemplateVo.getTemplate_id();
            url += "&sms_signature=" + URLEncoder.encode(subMailTemplateVo.getSms_signature(), "utf-8");
            url += "&sms_title=" + URLEncoder.encode(subMailTemplateVo.getSms_title(), "utf-8");
            url += "&sms_content=" + URLEncoder.encode(subMailTemplateVo.getSms_content(), "utf-8");
            putMethod.setRequestBody(url);
            putMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
            httpclient.executeMethod(putMethod);
            info = new String(putMethod.getResponseBody(), "utf-8");
            SubMailResult subMailResult = JSONUtil.toBean(JSONUtil.parseObj(info), SubMailResult.class);
            if ("success".equals(subMailResult.getStatus())) {
                isSuccess = true;
            } else {
                if (logger.isInfoEnabled()) {
                    logger.error("修改submail短信模板失败，错误代码：" + subMailResult.getCode() + "，错误信息：" + subMailResult.getMsg());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return isSuccess;
    }

    public boolean deleteTemplate(SubMailTemplate subMailTemplateVo) {
        String info;
        boolean isSuccess = false;
        try {
            HttpClient httpclient = new HttpClient();
            DeleteMethod deleteMethod = new DeleteMethod(submailConfig.getTemplateUrl());
            String url = "appid=" + submailConfig.getAppId() + "&signature=" + submailConfig.getAppKey();
            url += "&template_id=" + subMailTemplateVo.getTemplate_id();
            deleteMethod.setQueryString(url);
            deleteMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
            httpclient.executeMethod(deleteMethod);
            info = new String(deleteMethod.getResponseBody(), "utf-8");
            SubMailResult subMailResult = JSONUtil.toBean(JSONUtil.parseObj(info), SubMailResult.class);
            if ("success".equals(subMailResult.getStatus())) {
                isSuccess = true;
            } else {
                if (logger.isInfoEnabled()) {
                    logger.error("删除submail短信模板失败，错误代码：" + subMailResult.getCode() + "，错误信息：" + subMailResult.getMsg());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return isSuccess;
    }

    public boolean sendSubMailMessageNow(String projectId, SubMailMessages subMailMessageList) {
        if (submailConfig.isMock()) {
            return sendSubMailMessageMock(projectId, subMailMessageList);
        }
        String multi = "";
        if (subMailMessageList.getList() != null && !subMailMessageList.getList().isEmpty()) {
            multi = JSONUtil.toJsonStr(subMailMessageList.getList());
        }
        String info = null;
        HttpClient httpclient = new HttpClient();
        PostMethod post = new PostMethod(this.submailConfig.getSendUrl());
        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
        post.addParameter("appid", submailConfig.getAppId());
        post.addParameter("project", projectId);
        post.addParameter("multi", multi);
        post.addParameter("signature", submailConfig.getAppKey());
        try {
            httpclient.executeMethod(post);
            info = new String(post.getResponseBody(), "utf-8");
            logger.debug("短信接口返回：" + info);
            if (info != null && info.trim().startsWith("[")) {
                JSONArray jsonArray = JSONUtil.parseArray(info);
                for (int i = 0; i < jsonArray.size(); i++) {
                    SubMailResult messageResultVo = JSONUtil.toBean(JSONUtil.parseObj(jsonArray.get(i)), SubMailResult.class);
                    if ("success".equals(messageResultVo.getStatus())) {
                        if (logger.isInfoEnabled()) {
                            logger.info("成功发送短信给[" + messageResultVo.getTo() + "]");
                        }
                    } else {
                        String logContent = "发送短信给[" + messageResultVo.getTo() + "]失败";
                        if (logger.isInfoEnabled()) {
                            logger.error(logContent);
                        }
                    }
                }
                return true;
            } else {
                logger.error("发送短信错误，接口返回：" + info);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("发送短信模板（" + projectId + "）时发生错误，" + multi + "，接口返回：" + info, e);
            return false;
        }
    }
}
